<?php
namespace app\index\controller;
use think\Db;
use think\Controller;
use app\common\controller\PaylogBaseController;
use app\common\model\CorePayLog;



class Pay extends Controller
{
	
	public function index()
    {
       return  $this->fetch();
    }
	
	//充值成功
	function charge_success(){
		$longitude = 113.022014;
		$latitude = 25.779124;
    	
    	//获取订单信息
    	$cpay_log = db('log_paylog')
    				->where('order_sn',input('order_sn'))
    				->where('state',2)
    				->find();
    	//获取收款商家信息
    	$agent_info = db('info_agent')->where('id',$cpay_log['agent_id'])->find();
    	
    	//检查商家是否加入联盟
    	$where['b.state'] = 2;
    	$where['b.is_state'] = 1;
    	$where['a.agent_id'] = $agent_info['id'];
    	 
    	$list = db('union_member')
				->alias('a')
				->join('union_agent b','a.union_id = b.id')
				->where($where)
				->order('b.add_time desc')
				->select();
    	if(count($list)>0){
    		
    		$sql ='select *,ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$latitude.'*PI()/180-latitude*PI()/180)/2),2)+COS('.$latitude.'*PI()/180)*COS(latitude*PI()/180)*POW(SIN(('.$longitude.'*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli'.
							' from union_member  where agent_id = '.$agent_info['id'].' order by juli limit 1 ';
    		$union_info = Db::query($sql); 
    		
    		//获所有商家id 
    		$id_list = Db::table('union_member')->field('agent_id')->where('union_id',$union_info[0]['union_id'])->select();
    		$id_string ="";
    		foreach ($id_list as $key=>$value){
    			$id_string .= $value['agent_id'].",";
    		}
    		 $id_string = substr($id_string, 0,strlen($id_string)-1);
    		$sql ="select id,agent_name,address,logo,ad_score,".
							"ROUND(6378.138*2*ASIN(SQRT(POW(SIN((".$latitude."*PI()/180-latitude*PI()/180)/2),2)+COS(".$latitude."*PI()/180)*COS(latitude*PI()/180)*POW(SIN((".$longitude."*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli".
							" from info_agent where status =1  and ad_money>0.2 and id in (".$id_string.")  order by juli limit 5 ";
    	}else{
			$sql ='select id,agent_name,address,logo,ad_score,'.
							'ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$latitude.'*PI()/180-latitude*PI()/180)/2),2)+COS('.$latitude.'*PI()/180)*COS(latitude*PI()/180)*POW(SIN(('.$longitude.'*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli'.
							' from info_agent where status =1  and ad_money>0.2  order by juli limit 5 ';
    	}
    	
    	$agent_list = Db::query($sql);
    	$this->assign('agent_list',$agent_list);
    	$this->assign('cpay_log',$cpay_log);
    	
       	return  $this->fetch();
	}
	
	//鼓励金付款成功
    public function pay_success()
    {
    	//$longitude = input('longitude');
		//$latitude = input('latitude');
		$longitude = 113.022014;
		$latitude = 25.779124;
    	
    	//获取订单信息
    	$cpay_log = db('log_paylog')
    				->where('order_sn',input('order_sn'))
    				->where('state',2)
    				->find();
    	//获取收款商家信息
    	$agent_info = db('info_agent')->where('id',$cpay_log['agent_id'])->find();
    	
    	//检查商家是否加入联盟
    	$where['b.state'] = 2;
    	$where['b.is_state'] = 1;
    	$where['a.agent_id'] = $agent_info['id'];
    	 
    	$list = db('union_member')
				->alias('a')
				->join('union_agent b','a.union_id = b.id')
				->where($where)
				->order('b.add_time desc')
				->select();
    	if(count($list)>0){
    		
    		$sql ='select *,ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$latitude.'*PI()/180-latitude*PI()/180)/2),2)+COS('.$latitude.'*PI()/180)*COS(latitude*PI()/180)*POW(SIN(('.$longitude.'*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli'.
							' from union_member  where agent_id = '.$agent_info['id'].' order by juli limit 1 ';
    		$union_info = Db::query($sql); 
    		
    		//获所有商家id 
    		$id_list = Db::table('union_member')->field('agent_id')->where('union_id',$union_info[0]['union_id'])->select();
    		$id_string ="";
    		foreach ($id_list as $key=>$value){
    			$id_string .= $value['agent_id'].",";
    		}
    		 $id_string = substr($id_string, 0,strlen($id_string)-1);
    		$sql ="select id,agent_name,address,logo,ad_score,".
							"ROUND(6378.138*2*ASIN(SQRT(POW(SIN((".$latitude."*PI()/180-latitude*PI()/180)/2),2)+COS(".$latitude."*PI()/180)*COS(latitude*PI()/180)*POW(SIN((".$longitude."*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli".
							" from info_agent where status =1  and ad_money>0.2 and id in (".$id_string.")  order by juli limit 5 ";
    	}else{
			$sql ='select id,agent_name,address,logo,ad_score,'.
							'ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$latitude.'*PI()/180-latitude*PI()/180)/2),2)+COS('.$latitude.'*PI()/180)*COS(latitude*PI()/180)*POW(SIN(('.$longitude.'*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli'.
							' from info_agent where status =1  and ad_money>0.2  order by juli limit 5 ';
    	}
    	
    	$agent_list = Db::query($sql);
    	$this->assign('agent_list',$agent_list);
    	$this->assign('cpay_log',$cpay_log);
    	
       	return  $this->fetch();
    }
    
     //广告充值
    public function charge_ads()
    {
    	if(request()->isPost()){
    		//获取商家信息
    		$agent_info = db('info_agent')->where('id',input('agent_id'))->find();
    		if($agent_info){
    			return json(['code'=>200,'data'=>$agent_info]);
    		}else{
    			return json(['code'=>403,'msg'=>'商家不存在']);
    		}
    	}
    	
       return  $this->fetch();
    }
    
    //鼓励金充值
    public function charge_score()
    {
    	$type=get_brower_type();//判断是微信还是支付宝打开
    	$redirect='http://'.$_SERVER['HTTP_HOST'].'/index/pay/charge_score?agent_id='.input('agent_id').'&charge_type='.input('charge_type');
    	if($type==1){
			$auth_code=input("auth_code");
			$url ='https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=2017092808972929&scope=auth_base&redirect_uri='.urlencode($redirect);			
		}else{
			$auth_code=input("code");
			$url ='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wxpay_appid').'&redirect_uri='.urlencode($redirect).'&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect';
		}
		if(!$auth_code){
			Header("Location: $url");
			exit;
		}else{
			if($type==1){//支付宝openid
				$pay_type = 3;
				$field="alipay_id";
				$openid=user_ali_id($auth_code);
				
			}elseif($type==2){//微信openid
				$pay_type = 2;
				$field="openid";
				if(session('cut_auth_code') != $auth_code){
					session('cut_auth_code',$auth_code);
					$openid=user_wx_id($auth_code);
				}else{
					Header("Location: $url");
					exit;
				}
			}
			$agent_info = db('info_agent')->where('id',input('agent_id'))->find();	
			if($openid){
				$user=db('info_user')->where($field,$openid)->find();
				if(!$user){
					$data[$field]=$openid;
					$data['level']			= $agent_info['user_id'];
					$data['oem_id']			= $agent_info['oem_id'];
					$data['agency_id1']		= $agent_info['agency_id1'];
					$data['agency_id2']		= $agent_info['agency_id2'];
					$data['salesman_id']	= $agent_info['salesman_id'];
					$data['add_time']		= now_time();
					$user_id=Db::name('info_user')->insertGetId($data);
				}else{
					$user_id=$user['id'];
				}
			}
		}
    	if(!$agent_info){
    		echo "访问异常，商家不存在";exit;	
    	}
    	$pay_info['user_id']	=	$user_id;
    	$pay_info['agent_id']	=	$agent_info['id'];
    	$pay_info['pay_type']	=	$pay_type;
    	
    	
    	$cut_user_info = db('info_user')->where('id',$user_id)->find();
    	
    	session('info_user',$cut_user_info);
    	session('score_pay_info',$pay_info);
    	
    	$this->assign('agent_info',$agent_info);
    	
    	if(input('charge_type')){
    		if(input('charge_type') == 1){
    			return $this->fetch('pay/charge_score');
    		}else{
    			return $this->fetch('pay/charge_ads');
    		}
    	}
       return  $this->fetch();
    }
    
    
    function score_pay(){
    	if(request()->isPost()){
			$pay_info = session('score_pay_info');
			$pay_money = input('');
			if($pay_info){
				$agent_info = db('info_agent')->where('id',$pay_info['agent_id'])->find();
				$user_info  = db('info_user')->where('id',$pay_info['user_id'])->find();
				//订单编号
				$order_sn = order_create_no();
				if(input('charge_type')==1){	//积分充值
					//打印支付日志
					$result = $this->recharge_log($user_info['id'],$agent_info['id'],input('pay_money'),5,$order_sn,$pay_info['pay_type'],'用户'.$user_info['mobile'].'为商家'.$agent_info['cb_login_name'].'充值鼓励金',$agent_info['oem_id']);
				}else{ //广告充值
					//打印支付日志
					$result = $this->recharge_log($user_info['id'],$agent_info['id'],input('pay_money'),4,$order_sn,$pay_info['pay_type'],'用户'.$user_info['mobile'].'为商家'.$agent_info['cb_login_name'].'充值广告费',$agent_info['oem_id']);
				}
				
				if($result){
					$redirect_url = 'http://'.$_SERVER['HTTP_HOST'].'index/pay/charge_success?order_sn='.$order_sn;
					//发起支付
					if($pay_info['pay_type']==3){//支付宝
						if($agent_info['is_state'] == 1){
							$url=pay_code('H48007350000003','e1a870150cbccb203a3ed5841e84123d','2f9b3217d30f06966e69edeb53b74b8d',$pay_price,1,$order_sn,'',$redirect_url);
						}else{
							echo '支付失败';exit;
						}
					}elseif($pay_info['pay_type']==2) {//微信扫码
						
						if($agent_info['is_state'] == 1){
							$url=pay_code('H48007350000003','e1a870150cbccb203a3ed5841e84123d','2f9b3217d30f06966e69edeb53b74b8d',input('pay_money'),2,$order_sn,'',$redirect_url);
						}else{
							echo '支付失败';exit;
						}
					}
					return json(["code"=>200,"url"=>$url]);
				}
				
			}
    	}
    }
    
    function pay_test(){
    	$paylog = new PaylogBaseController();
		$paylog->print_log(input('order_sn'));
    }
    
    //计算付款金额
    function check_money(){
    	if(request()->isPost()){
			$origin_price = $_POST['origin_price'];	//应付金额
			$pay_price = $origin_price;				//实付金额	
			$pay_info = session('pay_info');
			if($pay_info){
				$agent_info = db('info_agent')->where('id',$pay_info['agent_id'])->find();
				$user_info  = db('info_user')->where('id',$pay_info['user_id'])->find();
				
				//是否开启积分营销
				if($agent_info['is_score'] == 1){
					//计算当前需付积分
					$need_score = bcmul($agent_info['ad_score']/100, $origin_price, 4);
					//检查用户积分实付充足
					if(bccomp($user_info['score'], $need_score, 4)>=0){	//抵扣积分
						//检查商家是否开启积分抵扣
						if($agent_info['ad_score']>0 && bccomp($origin_price, 1.00, 2)>=0){
							//计算实付金额
							$pay_price = bcsub($origin_price, $need_score, 2);
						}
					}else{//积分赠送
						//检查商家积分是否充足
						if(bccomp($agent_info['score'],$need_score,4)<0){
							//关闭商家积分营销
							db("info_agent")->where('id', $agent_info['id'])->update(['is_score' =>2]);
							
							$tem_w['title']='商家积分不足';
							$tem=db("sms_template")->where($tem_w)->find();
							$msg=sendsms($tem['sign_name'],$agent_info['mobile'],$tem['tid'],'code','');
							
							return json(["code"=>400,'msg'=>'商家积分不足，无法赠送积分']);		
						}
					}
				}
				$order_sn = order_create_no();
				//打印支付日志
				$result = $this->record_log($pay_info['user_id'],$pay_info['agent_id'],$pay_info['store_id'],$pay_info['clerk_id'],
							$pay_price,2,$order_sn,$pay_info['pay_type'],1,'扫码付款',0,$origin_price,$agent_info['oem_id'],2,
							$agent_info['salesman_id'],$agent_info['agency_id1'],$agent_info['agency_id2']);
				if($result){
					//发起支付
					if($pay_info['pay_type']==3){//支付宝
						if($agent_info['is_state'] == 1){
							$url=pay_code($agent_info['cb_no'],$agent_info['cb_miyao'],$agent_info['cb_clerk'],$pay_price,1,$order_sn,'');
						}else{
							echo '支付失败';exit;
						}
					}elseif($pay_info['pay_type']==2) {//微信扫码
						
						if($agent_info['is_state'] == 1){
							$url=pay_code($agent_info['cb_no'],$agent_info['cb_miyao'],$agent_info['cb_clerk'],$pay_price,2,$order_sn,'');
						}else{
							echo '支付失败';exit;
						}
					}
					return json(["code"=>200,"url"=>$url]);
				}
				
			}
    	}
    }
    
    //二维码付款
    function qrcode_pay(){
    	$type=get_brower_type();//判断是微信还是支付宝打开
    	$redirect='http://'.$_SERVER['HTTP_HOST'].'/index/pay/qrcode_pay?agent_id='.input('agent_id').'&store_id='.input('store_id').'&clerk_id='.input('clerk_id');
    	if($type==1){
			$auth_code=input("auth_code");
			$url ='https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=2017092808972929&scope=auth_base&redirect_uri='.urlencode($redirect);			
		}else{
			$auth_code=input("code");
			$url ='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wxpay_appid').'&redirect_uri='.urlencode($redirect).'&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect';
		}
		if(!$auth_code){
			Header("Location: $url");
			exit;
		}else{
			if($type==1){//支付宝openid
				$pay_type = 3;
				$field="alipay_id";
				$openid=user_ali_id($auth_code);
				
			}elseif($type==2){//微信openid
				$pay_type = 2;
				$field="openid";
				if(session('cut_auth_code') != $auth_code){
					session('cut_auth_code',$auth_code);
					$openid=user_wx_id($auth_code);
				}else{
					Header("Location: $url");
					exit;
				}
			}
			$agent_info = db('info_agent')->where('id',input('agent_id'))->find();	
			if($openid){
				$user=db('info_user')->where($field,$openid)->find();
				if(!$user){
					$data[$field]=$openid;
					$data['level']			= $agent_info['user_id'];
					$data['oem_id']			= $agent_info['oem_id'];
					$data['agency_id1']		= $agent_info['agency_id1'];
					$data['agency_id2']		= $agent_info['agency_id2'];
					$data['salesman_id']	= $agent_info['salesman_id'];
					$data['add_time']		= now_time();
					$user_id=Db::name('info_user')->insertGetId($data);
				}else{
					$user_id=$user['id'];
				}
			}
		}
    	if(!$agent_info){
    		echo "访问异常，商家不存在";exit;	
    	}
    	$pay_info['user_id']	=	$user_id;
    	$pay_info['agent_id']	=	$agent_info['id'];
    	$pay_info['store_id']	=	input('store_id');
    	$pay_info['clerk_id']	=	input('clerk_id');
    	$pay_info['pay_type']	=	$pay_type;
    	
    	
    	$cut_user_info = db('info_user')->where('id',$user_id)->find();
    	
    	session('info_user',$cut_user_info);
    	session('pay_info',$pay_info);
    	
    	$this->assign('agent_info',$agent_info);
    	
    	return  $this->fetch();
    }
    
    public function qrcode_pay2()
    {
    /**
	 * 获取支付宝支付二维码支付
	 */
	 require_once '/extend/dpay/f2fpay/model/builder/AlipayTradePrecreateContentBuilder.php';
	 require_once '/extend/dpay/f2fpay/service/AlipayTradeService.php';
//		import('dpay.f2fpay.model.builder.AlipayTradePrecreateContentBuilder');
//		import('dpay.f2fpay.service.AlipayTradeService');
		$qrPayRequestBuilder = new \AlipayTradePrecreateContentBuilder();
		$qrPay = new \AlipayTradeService($config);
		$providerId = "2088021044805134"; //系统商pid,作为系统商返佣数据提取的依据
		$extendParams = new \ExtendParams();
		$extendParams->setSysServiceProviderId($providerId);
		$extendParamsArr = $extendParams->getExtendParams();
		
		// 支付超时，线下扫码交易定义为5分钟
		$timeExpress = "5m";
		// 创建请求builder，设置请求参数
			//第三方应用授权令牌,商户授权系统商开发模式下使用
		$sell_id="2088102242613573";
		$appAuthToken = "201709BB522f469ee5a9406091fad8f66ccf3X57";//根据真实值填写
		$qrPayRequestBuilder->setSellerId($sell_id);
		$qrPayRequestBuilder->setAppAuthToken($appAuthToken);
		$qrPayRequestBuilder->setOutTradeNo("243533");
		$qrPayRequestBuilder->setTotalAmount(0.01);
		$qrPayRequestBuilder->setTimeExpress($timeExpress);
		$qrPayRequestBuilder->setSubject('消费');
		$qrPayRequestBuilder->setBody("消费");
		//$qrPayRequestBuilder->setUndiscountableAmount($undiscountableAmount);
		//$qrPayRequestBuilder->setExtendParams($extendParamsArr);
		// 调用qrPay方法获取当面付应答
		$qrPayResult = $qrPay->qrPay($qrPayRequestBuilder);
			//	根据状态值进行业务处理
			switch ($qrPayResult->getTradeStatus()){
				case "SUCCESS":
					$response = $qrPayResult->getResponse();
					$qrcode= 'http://www.vshop88.net/code/code.php?url='.urlencode($response->qr_code).'&margin=1&size=10';
					$qrcode= 'http://www.vshop88.net/code/code.php?url='.urlencode($response->qr_code).'&margin=1&size=10';
			//$qrcode = $qrPay->create_erweima($response->qr_code);
			echo "<img src=$qrcode />";
					return $qrcode;
					break;
				case "FAILED":
					break;
				case "UNKNOWN":
					if($qrPayResult->getResponse()){
						print_r($qrPayResult->getResponse());
					}
					break;
				default:
					echo "不支持的返回状态，创建订单二维码返回异常!!!";
					break;
			}
       return  $this->fetch();
    }
    
    /**
	 * 判断订单是否已经支付过
	 */
	public function check_order(){
		$where['sn']=input('WIDout_trade_no');
		$where['status']=2;
		$paylog=db("mall_paylog")->where($where)->find();
		if($paylog){
			return $this->toJson(408, '请勿重复支付');
		}
	}
	
	//充值日志()
	function recharge_log($user_id,$agent_id,$balance,$order_type,$order_sn,$pay_type,$message,$oem_id){
		$agent_info = db('info_agent')->where('id',input('agent_id'))->find();
		//充值日志
		$credit_data = array(
			'uid'			=> $user_id,
			'agent_id' 		=> $agent_id,
			'balance'		=> $balance,
			'order_type' 	=> $order_type,
			'order_sn' 		=> $order_sn,
			'pay_type' 		=> $pay_type,
			'state' 		=> 1,
			"message"		=> $message,
			"order_id"		=> 0,
			"oem_id"		=> $oem_id,
			'add_time' 		=> now_time(),
		);
			
		$res= db('log_paylog')->insert($credit_data);
		
		return $res;
	}
	
	//打印支付日志
	function record_log($user_id,$agent_id,$chain_id,$clerk_id,$balance,
	$order_type,$order_sn,$pay_type,$state,$message,$order_id,$origin_price,
	$oem_id,$sy_type,$salesman_id,$agency_id1,$agency_id2){
		$data['uid']			=$user_id;
		$data['agent_id']		=$agent_id;
		$data['chain_id']		=$chain_id;
		$data['clerk_id']		=$clerk_id;
		$data['balance']		=$balance;
		$data['order_type']		=$order_type;
		$data['order_sn']		=$order_sn;
		$data['pay_type']		=$pay_type;
		$data['state']			=$state;
		$data['message']		=$message;
		$data['order_id']		=$order_id;
		$data['origin_price']	=$origin_price;
		$data['oem_id']			=$oem_id;
		$data['add_time']		=now_time();
		$data['sy_type']		=$sy_type;
		$data['salesman_id']	=$salesman_id;
		$data['agency_id1']		=$agency_id1;
		$data['agency_id2']		=$agency_id2;
		
		$res=db('log_paylog')->insert($data);
		return $res;
		
	}
	
	
	
    
}
